﻿using ToolKitIESiteList.Library;
using ToolKitManagerIESiteList.UserControls;
using ToolKitManagerIESiteList.Util;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics.CodeAnalysis;

namespace ToolKitManagerIESiteList
{
    public partial class FrmLoadSiteDiscovery : Form
    {
        private enum StateTab
        {
            Files,
            Domains
        }

        private StateTab currentStateTab;
        private DataDiscovery[] ImportedFiles;


        public FrmLoadSiteDiscovery()
        {
            InitializeComponent();
        }

        [SuppressMessage("Microsoft.Design", "CA1031")]
        [SuppressMessage("Microsoft.Reliability", "CA2000")]
        private void BntSelectFiles_Click(object sender, EventArgs e)
        {
            //Exibe a caixa de seleção
            if (opdDiscoveryFile.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < opdDiscoveryFile.FileNames.Length; i++)
                {
                    try
                    {
                        HelperEmie.ValidateSchemeSiteDiscovery(opdDiscoveryFile.FileNames[i]);
                    }
                    catch (Exception ex)
                    {
                        this.ShowError(string.Format("{0}.{1}:{2}", Properties.Resources.ErrorValidateScheme, opdDiscoveryFile.FileNames[i], ex.Message), AssemblyHelper.AssemblyTitle);
                        return;
                    }
                }
                foreach (var selectedFile in opdDiscoveryFile.FileNames)
                {
                    var item = new FileSiteDiscovery(selectedFile);
                    item.Width = PanelFiles.Width - 40;
                    item.ItemRemoved += Item_ItemRemoved;
                    flowLayoutFiles.Controls.Add(item);
                }
            }
            BntLoadFiles.Enabled = (flowLayoutFiles.Controls.Count > 0);
        }
        private void Item_ItemRemoved(object sender, EventArgs e)
        {
            flowLayoutFiles.Controls.Remove(sender as Control);
            BntLoadFiles.Enabled = (flowLayoutFiles.Controls.Count > 0);
        }

        private void FrmLoadSiteDiscovery_Load(object sender, EventArgs e)
        {
            BntLoadFiles.Enabled = false;
            TabControl.SelectTab(TabFiles);
            currentStateTab = StateTab.Files;
            UpdateStateButton(TabFiles);
            PanelHideTab.Top = 0;
            PanelHideTab.BringToFront();
            LnkeditFilters.Enabled = Properties.Settings.Default.RemoveExtFilter;
            LnkEditDomain.Enabled = Properties.Settings.Default.RemoveDomFilter;
            LnkFilterDomain.Enabled = Properties.Settings.Default.RemoveDomFilter;
        }
        private void BntLoadFiles_Click(object sender, EventArgs e)
        {
            var files = flowLayoutFiles.Controls
                .Cast<FileSiteDiscovery>()
                .Select(item => item.FileName)
                .ToArray();

            ImportedFiles = SiteDiscovery.Load(files);

            ChkLstDomains.Items.Clear();
            ChkLstDomains.Items.AddRange(SiteDiscovery.ListDomains(ImportedFiles)
                .OrderBy(a => a)
                .ToArray());
            var excludeDomains = Properties.Settings.Default.ExcludeDomains
                .Cast<string>()
                .ToArray();
            for (int i = 0; i < ChkLstDomains.Items.Count; i++)
            {
                if (Properties.Settings.Default.RemoveDomFilter)
                {
                    if (!excludeDomains.Contains(ChkLstDomains.Items[i].ToString()))
                    {
                        ChkLstDomains.SetItemChecked(i, true);
                    }
                }
                else
                {
                    ChkLstDomains.SetItemChecked(i, true);
                }
            }
            if (Properties.Settings.Default.RemoveDomFilter)
            {
                LnkFilterDomain.Enabled = (ChkLstDomains.Items.Count - ChkLstDomains.CheckedItems.Count != 0);
            }
            flowLayoutFiles.Controls.Clear();
            currentStateTab = StateTab.Domains;
            TabControl.SelectTab(TabDomains);
        }

        private void UpdateStateButton(TabPage currentTab)
        {
            BntLoadFiles.Enabled = (currentTab == TabFiles && flowLayoutFiles.Controls.Count > 0);
            BntSelectFiles.Enabled = (currentTab == TabFiles);
            BntImport.Enabled = (currentTab == TabDomains);
        }

        private void TabControl_Selected(object sender, TabControlEventArgs e)
        {
            UpdateStateButton(e.TabPage);
        }


        private void TabControl_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (e.TabPage == TabFiles && currentStateTab != StateTab.Files)
            {
                e.Cancel = true;
            }
            else if (e.TabPage == TabDomains && currentStateTab != StateTab.Domains)
            {
                e.Cancel = true;
            }
        }

        private void BntImport_Click(object sender, EventArgs e)
        {
            var domainsRemove = new List<string>();
            for (int i = 0; i < ChkLstDomains.Items.Count; i++)
            {
                if (!ChkLstDomains.GetItemChecked(i))
                {
                    domainsRemove.Add(ChkLstDomains.Items[i].ToString());
                }
            }

            if (domainsRemove.Count > 0)
            {
                var entriesDel = ImportedFiles
                    .AsEnumerable()
                    .Where(d => domainsRemove.Contains(d.Url.GetHostAndPort()))
                    .Select(s =>
                    {
                        var mode = CompatMode.IE11;
                        if (!Enum.TryParse("IE" + s.DocMode, out mode))
                        {
                            mode = CompatMode.Default;
                        }
                        return new IEModeDataItem
                        {
                            AbsolutePath = s.Url.AbsolutePath,
                            HostPort = s.Url.GetHostAndPort(),
                            Comment = string.Empty,
                            CompatMode = mode,
                            IsLogicalDuplicate = false,
                            OpenIn = OpenIn.IE11,
                            OriCompatMode = mode,
                            OriOpenIn = OpenIn.IE11,
                            Uri = s.Url
                        };
                    });
                ManagerHotTracker.AddTraker(ActionTracker.ImportSiteDiscovery, Properties.Resources.RemoveDomainFilter, Properties.Resources.ImportedSiteDiscovery, entriesDel);
            }

            ImportedFiles = SiteDiscovery.Sanitize(ImportedFiles, domainsRemove.ToArray()).ToArray();

            var iesites = new List<IEMXmlItem>();
            foreach (var item in ImportedFiles)
            {
                var mode = CompatMode.IE11;
                if (!Enum.TryParse("IE" + item.DocMode, out mode))
                {
                    mode = CompatMode.Default;
                }
                iesites.Add(new IEMXmlItem()
                {
                    Uri = item.Url,
                    CompatMode = mode,
                    OpenIn = OpenIn.IE11
                });
            }
            EmieDocument.TempEmieDocument = new MemoryStream();
            SiteDiscovery.MakeEMIESiteList(iesites, EmieDocument.TempEmieDocument);
            this.DialogResult = DialogResult.OK;
            Close();
        }

        private void BntClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            EmieDocument.ClearTempEmieDocument();
            Close();
        }

        private void ChkLstDomains_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            var dif = 0;
            if (e.NewValue == CheckState.Checked)
            {
                dif = 1;
            }
            else if (e.NewValue == CheckState.Unchecked)
            {
                dif = -1;
            }
            if (Properties.Settings.Default.RemoveDomFilter)
            {
                LnkFilterDomain.Enabled = (ChkLstDomains.Items.Count - (ChkLstDomains.CheckedItems.Count + dif) != 0);
            }
        }

        private void LnkFilterDomain_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var excludeDomains = Properties.Settings.Default.ExcludeDomains
                .Cast<string>()
                .ToList();
            var qtd = 0;
            for (int i = 0; i < ChkLstDomains.Items.Count; i++)
            {
                if (!ChkLstDomains.GetItemChecked(i))
                {
                    if (!excludeDomains.Contains(ChkLstDomains.Items[i].ToString()))
                    {
                        qtd++;
                        excludeDomains.Add(ChkLstDomains.Items[i].ToString());
                    }
                }
            }
            StringCollection collection = new StringCollection();
            collection.AddRange(excludeDomains.ToArray());
            Properties.Settings.Default.ExcludeDomains = collection;
            Properties.Settings.Default.Save();
            if (qtd > 0)
            {
                this.ShowInformation(string.Format(Properties.Resources.AddedFilters, qtd), AssemblyHelper.AssemblyTitle);
            }
        }

        private void LnkeditFilters_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (var frm = new FrmEditFilterExtension())
            {
                frm.ShowDialog(this);
            }
        }

        private void LnkEditDomain_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (var frm = new FrmEditFilterDomains())
            {
                frm.ShowDialog(this);
            }
            var excludeDomains = Properties.Settings.Default.ExcludeDomains
                .Cast<string>()
                .ToArray();
            for (int i = 0; i < ChkLstDomains.Items.Count; i++)
            {
                if (!excludeDomains.Contains(ChkLstDomains.Items[i].ToString()))
                {
                    ChkLstDomains.SetItemChecked(i, true);
                }
            }
        }
    }
}
